<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  layout: 'custom',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
    enablePullDownRefresh: true, // ✅ 启用下拉刷新
  },
}
</route>
<template>
  <view style="height: 100vh">
    <view class="bgContainer">
      <view class="bg-wrapper">
        <image class="bgImage" :src="backgroundImage" mode="widthFix" />
        <image class="bgColor" :src="appBackgroundColor" mode="widthFix" />
        <image class="bgLogo" :src="appLogo" mode="widthFix" />
        <view class="bgTextZH">我对代表说句话</view>
        <view class="bgTextTibetan" v-if="showTibetan">བོད་ཀྱི་སྐདབོད་ཀྱི་སྐདབོད་ཀྱི་སྐད</view>
      </view>
    </view>

    <view class="mt-4">
      <wd-status-tip image="content" tip="暂无人大代表信息" v-if="!dataList.length" />
      <wd-card v-for="(item, index) in dataList" :key="item.id">
        <view class="flex py-2" @click="toRepDetail(item.id)">
          <view style="width: 30%">
            <image
              v-if="item.src"
              :src="item.src"
              mode="widthFix"
              style="border-radius: 5px"
            ></image>
          </view>
          <view class="content-person flex flex-col flex-1 p-2 justify-between">
            <view class="flex justify-between">
              <view class="text-black zh-tb-text">
                <text>{{ item.name }}</text>
                <text>{{ item.tibetanName }}</text>
              </view>
              <view class="content-button" @click.stop="toProtocol(item.id)">
                <text>{{ t('SAY_TO_REP.zh') }}</text>
                <text v-if="showTibetan">{{ t('SAY_TO_REP.bo') }}</text>
              </view>
            </view>
            <view class="zh-tb-text text-#888">
              <text>{{ item.position }}</text>
              <text style="color: #888">{{ item.tibetanPosition }}</text>
            </view>
          </view>
        </view>
      </wd-card>
    </view>
  </view>
</template>

<script setup lang="ts">
import { t } from '@/locale/index'
import { onLoad, onShow, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { ref, onMounted, computed } from 'vue'
import { representativeList, repPositionList } from '@/api/representative'
import { useUserStore } from '@/store/user'
import { useTenantStore } from '@/store/tenant'

const store = useUserStore() // 获取 Vuex store
const tenantStore = useTenantStore()

const defaultBackground = import.meta.env.VITE_APP_BG_GH3 || '/static/bgGH3.jpg'
const tenant = computed(() => tenantStore.tenantInfo)
const backgroundImage = computed(() =>
  showTibetan ? appBackgroundXH : tenant.value.logoUrl || defaultBackground,
)

// 获取环境变量
const showTibetan = import.meta.env.VITE_SHOW_TIBETAN === 'true'
const appTitle = ref(import.meta.env.VITE_APP_TITLE || 'Unibest Login')
const appLogo = ref(import.meta.env.VITE_APP_LOGO || '/static/logo.png')
const appBackgroundXH = ref(import.meta.env.VITE_APP_BG_XH || '/static/bgXH.png')

const appBackgroundGH = ref(import.meta.env.VITE_APP_BG_GH1 || '/static/bgGH1.png')
// const appBackgroundGH = ref(import.meta.env.VITE_APP_BG_GH2 || '/static/bgGH2.jpg')
// const appBackgroundGH = ref(import.meta.env.VITE_APP_BG_GH3 || '/static/bgGH3.jpg')

const appBackgroundColor = ref(import.meta.env.VITE_APP_LOGO || '/static/bgcolor.png')
let isFirstLoad = true // 标志位，避免重复加载
const isLastPage = ref(false)
const isLoading = ref(false) // 避免重复请求
const positionList = ref<any[]>([])
const pageParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
})
const dataList = ref<any[]>([
  // {
  //   src: '/static/deputies/4.png',
  //   name: '赵美玲',
  //   tibetanName: 'ཀྲོ་མེ་ལེན།',
  //   position: '县镇级人大代表',
  //   tibetanPosition: 'རྫོང་རིམ་པའི་དམངས་ཆེན་འཐུས་མི།',
  // },
  // {
  //   src: '/static/deputies/5.png',
  //   name: '尕藏成勒',
  //   tibetanName: 'སྐལ་བཟང་འཕྲིན་ལས།',
  //   position: '县镇级人大代表',
  //   tibetanPosition: 'རྫོང་རིམ་པའི་དམངས་ཆེན་འཐུས་མི།',
  // },
  // {
  //   src: '/static/deputies/1.png',
  //   name: '才项',
  //   tibetanName: 'སྐལ་བཟང་འཕྲིན་ལས།',
  //   position: '县镇级人大代表',
  //   tibetanPosition: 'རྫོང་རིམ་པའི་དམངས་ཆེན་འཐུས་མི།',
  // },
  // {
  //   src: '/static/deputies/2.png',
  //   name: '金光红',
  //   tibetanName: 'སྐལ་བཟང་འཕྲིན་ལས།',
  //   position: '州县镇级人大代表',
  //   tibetanPosition: 'རྫོང་རིམ་པའི་དམངས་ཆེན་འཐུས་མི།',
  // },
  // {
  //   src: '/static/deputies/3.png',
  //   name: '翟增荣',
  //   tibetanName: 'སྐལ་བཟང་འཕྲིན་ལས།',
  //   position: '县镇级人大代表',
  //   tibetanPosition: 'རྫོང་རིམ་པའི་དམངས་ཆེན་འཐུས་མི།',
  // },
])
const tenantId = ref(null)
onLoad(async (options) => {
  console.log('tenant', tenant)
  console.log('tenantStore', tenantStore)
  pageParams.value.tenantId = tenant.value.tenantId
  await getPositionList()
  fetchDataList(true)
  isFirstLoad = false
})
onShow(() => {
  pageParams.value.tenantId = tenant.value.tenantId
  // 不是首次时才触发刷新（避免重复请求）
  if (!isFirstLoad) {
    fetchDataList(true) // 传 true 代表刷新模式
  }
})

const toFeedback = () => {
  console.log('点击了')
  uni.navigateTo({ url: `/pages/register/index` })
}
const toProtocol = (id) => {
  console.log('id', id)

  uni.navigateTo({ url: `/pages/index/protocol?representativeId=${id}` })
}
const toRepDetail = (id: number) => {
  uni.navigateTo({ url: `/pages/index/detail?id=${id}` })
}
const getPositionList = async () => {
  try {
    const res = await repPositionList()
    if (res.code === 0) {
      positionList.value = res.data
    }
  } catch (error) {}
}
//获取列表数据
const fetchDataList = async (isRefresh = false) => {
  if (isLoading.value || (isLastPage.value && !isRefresh)) return

  isLoading.value = true

  if (isRefresh) {
    pageParams.value.pageNum = 1
    isLastPage.value = false
  }

  try {
    const res = await representativeList(pageParams.value)
    if (res.code === 0) {
      const resultList = res.data || []
      const mappedList = resultList.map((item) => ({
        id: item.representativeId,
        src: item.avatarUrl,
        name: item.name,
        tibetanName: item.nameZw,
        intro: item.intro,
        tibetanIntro: item.introZw,
        position: positionList.value.find((p) => p.groupId === item.groupId)?.groupName,
        tibetanPosition: positionList.value.find((p) => p.groupId === item.groupId)
          ?.groupTibetanName,
      }))

      if (isRefresh) {
        dataList.value = mappedList
      } else {
        dataList.value = [...dataList.value, ...mappedList]
      }

      // 判断是否是最后一
      if (mappedList.length < pageParams.value.pageSize) {
        isLastPage.value = true
      } else {
        pageParams.value.pageNum += 1
      }
    }
  } catch (error) {
    console.error(error)
  } finally {
    isLoading.value = false
    if (isRefresh) uni.stopPullDownRefresh() // 停止下拉刷新动画
  }
}
onPullDownRefresh(() => {
  fetchDataList(true)
})

onReachBottom(() => {
  fetchDataList(false)
})
</script>

<style lang="scss">
.bg-wrapper {
  position: relative;
  width: 100%;
}

.bgImage,
.bgColor {
  width: 100%;
  display: block;
}

.bgColor {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  pointer-events: none; // ✅ 不拦截点击事件
}

.bgLogo {
  position: absolute;
  top: 18%;
  left: 6%;
  z-index: 2;
  width: 24%;
}

.bgTextZH {
  position: absolute;
  top: 42%;
  right: 5%;
  z-index: 2;
  font-size: 50rpx;
  font-weight: 600;
  color: #fff;
  letter-spacing: 2rpx;
}

.bgTextTibetan {
  position: absolute;
  top: 30%;
  right: 3%;
  z-index: 2;
  font-size: 48rpx;
  font-weight: 600;
  color: #fff;
}

.content {
  display: flex;
  // justify-content: space-between;
  padding: 5px 0;
}

// .content-person {
//   display: flex;
//   flex-direction: column;
//   justify-content: space-between;
//   text-align: left;
//   padding: 20rpx 0;
// }

.content-button {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  width: 100px;
  height: 60px;
  text-align: center;
  // padding: 0 5px;
  border: 1px solid #ccc;
  color: #000;
}
</style>
